package com.shen.utils;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import static com.shen.constant.CsvConstant.COMMA_CHAR;
import static com.shen.constant.CsvConstant.GBK_CHARSET;

/**
 * csv文件读写工具类
 */
@Slf4j
public class CsvFileUtil {
    private CsvFileUtil() {
    }

    /**
     * 读取csv文件中第一列的内容存入集合
     *
     * @param filePath 文件路径
     * @return 集合
     */
    public static List<String> readCsvFile(String filePath) {
        List<String> jgmcList = new ArrayList<>(1 << 8);
        try {
            //创建Csv实例
            CsvReader csvReader = new CsvReader(filePath, COMMA_CHAR, Charset.forName(GBK_CHARSET));
            //读取数据
            while (csvReader.readRecord()) {
                //仅遍历第一列
                String jgmc = csvReader.get(0);
                log.info("[csv文件读取]: 机构名称:{}", jgmc);
                jgmcList.add(jgmc);
            }
            csvReader.close();
        } catch (Exception e) {
            log.error("[csv文件读取] csv文件读取异常:", e);
        }
        return jgmcList;
    }

    /**
     * 将根据机构名称查询到的地理信息写入csv文件中
     *
     * @param filePath   待写入的csv文件
     * @param geoInfos   地理信息集合
     * @param csvHeaders 列属性名
     */
    public static void writeCsvFile(String filePath, List<String[]> geoInfos, String[] csvHeaders) {
        CsvWriter csvWriter = new CsvWriter(filePath, COMMA_CHAR, Charset.forName(GBK_CHARSET));
        try {
            //写入列属性名与行记录
            csvWriter.writeRecord(csvHeaders);
            for (String[] geoInfo : geoInfos) {
                csvWriter.writeRecord(geoInfo);
            }
            csvWriter.close();
        } catch (Exception e) {
            log.error("[写入csv文件] 写入csv文件异常", e);
        }

    }

    public static void writeCsvFile1(String filePath, List<String[]> geoInfos, String[] csvHeaders) {
        CsvWriter csvWriter = new CsvWriter(filePath, COMMA_CHAR, Charset.forName(GBK_CHARSET));
        try {
            //写入列属性名与行记录
            csvWriter.writeRecord(csvHeaders);
            for (String[] geoInfo : geoInfos) {
                csvWriter.writeRecord(geoInfo);
            }
            csvWriter.close();
        } catch (Exception e) {
            log.error("[写入csv文件] 写入csv文件异常", e);
        }

    }
}
